package com.lagou.rpc.client;

import com.lagou.rpc.zk.ZkClient;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class RoundRobinLoadBalance implements LoadBalance {
    AtomicInteger index = new AtomicInteger();
    final ZkClient zkClient;
    private Logger log = LoggerFactory.getLogger(LoadBalance.class);
    public RoundRobinLoadBalance(ZkClient zkClient) {
        this.zkClient = zkClient;
    }
    @Override
    public String doSelect(String url, List<String> child) {
        LinkedList<Long> timeList = new LinkedList<>();
        for (String str : child) {

            long lastTime = NumberUtils.toLong(zkClient.getContent("/rpc/" + str + ".lastTime"));
            if (lastTime == 0) {
                continue;
            }
            timeList.add(lastTime);
        }
        int childSize = child.size();
        int timeSize = timeList.size();
        if (timeSize != childSize)  {
            String server = child.get(index.incrementAndGet() % child.size());
            log.info("server:" + server + ",timeout:0");
            return server;
        } else {
            // 以下开始选出响应时间最小的server。
            int index = 0;
            for (int i = 1; i < timeList.size(); i++) {
                if (timeList.get(i) < timeList.get(index)) {
                    index = i;
                }
            }

            String minServer = child.get(index);
            log.info("server:" + minServer + ",timeout:" + timeList.get(index));
            return minServer;
        }
    }

}
